#include <iostream>
#include <vector>
#include <thread>
#include <functional>
#include <mutex>

using namespace std;

// 定义一个Thread类，用来创建线程并执行
class Thread
{
public:
    using PFUNC = function<void(int)>;
    Thread(PFUNC&& func, const int& id):_pfunc(func),ID(id) {}
    thread Start(void)
    {
        thread t(this->_pfunc, this->ID);
        return t;
    }
private:
    PFUNC _pfunc;
    int ID;
};

// 定义一个ThreadPool类，用来管理线程
class ThreadPool
{
public:
    ThreadPool() {}
    ~ThreadPool() 
    {
        for(Thread* &pth : _pool)
            delete pth;
    }
    void StartPool(int size)
    {
        for(int i = 0; i < size; i ++)
            this->_pool.push_back(
                new Thread(bind(&ThreadPool::RunInThread, this, placeholders::_1), i)
            );
        for(int i = 0; i < size; i ++)
            this->_handler.push_back(this->_pool[i]->Start());
        for(thread &th : this->_handler)
            th.join();
    }
private:
    vector<Thread*> _pool; // 定义线程池存储线程指针
    vector<thread> _handler; // 定义线程执行的函数句柄
    mutex _mtx;
    void RunInThread(int id)
    {
        unique_lock<mutex> lock(this->_mtx);
        cout << "当前线程ID是: " << id << "正在执行" << endl;
        std::this_thread::sleep_for(std::chrono::milliseconds(500));
    }
};


int main(int argc, char const *argv[])
{
    ThreadPool pool;
    pool.StartPool(15);
    return 0;
}
